package com.ibm.iisp.common.spring;

import java.beans.PropertyDescriptor;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.InvalidPropertyException;

public class ConfigBeanProcessor {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String prefix;
	private Object conf;
	public void processConfigBeans() {
		Map<String, String> propMap = CustomPropertyPlaceholderConfigurer.getPropertiesData();
		BeanWrapper bean = new BeanWrapperImpl(conf);
		for (Map.Entry<String, String> ent : propMap.entrySet()) {
			String propName = ent.getKey();
			String _val = ent.getValue();
			logger.debug("Prop: {}, value: {}", propName, _val);
			if (propName.startsWith(prefix)) {
				propName = propName.substring(prefix.length() + 1);
				try {
					bean.setPropertyValue(propName, _val);
				}catch (InvalidPropertyException e) {
					
					logger.warn("Cannot set prop {}@{}", propName, conf.getClass());
					int dotIdx = propName.lastIndexOf(".");
					if (dotIdx > 0) {
						String mapPropName = propName.substring(0, dotIdx);
						tryMapProps(bean, propName, mapPropName, _val);
					}
				}
			}
		}
	}
	private void tryMapProps(BeanWrapper bean, String propName, String mapPropName, Object val) {
		try {
			PropertyDescriptor pd = bean.getPropertyDescriptor(mapPropName);
			if (pd.getPropertyType().isAssignableFrom(Map.class)) {
				@SuppressWarnings("unchecked")
				Map<String, Object> map = (Map<String, Object>) bean.getPropertyValue(mapPropName);
				String key = propName.substring(mapPropName.length() + 1);
				map.put(key, val);
				logger.trace("Put value {}={} to {}", key, val, mapPropName);
			}
		}catch (InvalidPropertyException e) {
			logger.trace("prop invalid:{}", mapPropName);
			int dotIdx = mapPropName.lastIndexOf(".");
			if (dotIdx > 0) {
				mapPropName = mapPropName.substring(0, dotIdx);
				tryMapProps(bean, propName, mapPropName, val);
			}
		}
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	public void setConf(Object conf) {
		this.conf = conf;
	}
}
